package org.wenhuayuan.project.common.view

import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.widget.ImageView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.bumptech.glide.load.resource.bitmap.CircleCrop
import com.bumptech.glide.load.resource.bitmap.RoundedCorners

fun ImageView.loadUrl(url: String) {
    Glide.with(this).load(url).into(this)
}

fun ImageView.loadCircle(url: String) {
    Glide.with(this).load(url).transform(CenterCrop()).into(this)
}

// 踩坑：glide 图片裁剪与ImageView的ScaleType有冲突
fun ImageView.loadCorner(url: String, corner: Int) {
    Glide.with(this).load(url).transform(CenterCrop(), RoundedCorners(corner)).into(this)
}

fun ImageView.loadCircleBorder(url: String, borderWidth: Float = 0f, borderColor: Int = Color.WHITE) {
    Glide.with(this).load(url).transform(CircleBorderTransform(borderWidth, borderColor)).into(this)
}

class CircleBorderTransform(val borderWidth: Float, val borderColor: Int) : CircleCrop() {
    private var borderPaint = Paint(Paint.ANTI_ALIAS_FLAG)
    init {
        borderPaint.setColor(borderColor)
        borderPaint.strokeWidth = borderWidth
        borderPaint.style = Paint.Style.STROKE
    }

    override fun transform(
        pool: BitmapPool,
        toTransform: Bitmap,
        outWidth: Int,
        outHeight: Int
    ): Bitmap {
        val tansform =  super.transform(pool, toTransform, outWidth, outHeight)
        val canvas = Canvas(tansform)

        val halfW = outWidth/2.toFloat()
        val halfH = outHeight/2.toFloat()

        canvas.drawCircle(halfW, halfH, Math.min(halfW, halfH) - borderWidth/2, borderPaint)

        canvas.setBitmap(null)

        return tansform
    }
}

